package webapi

import (
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/helplib"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/wonderivan/logger"
)

//LogfileService 网关服务器注册API类。注册控制台
type LogfileService struct {
	base ServiceBase
}

//Regist 注册
func (_this *LogfileService) Regist(mux *http.ServeMux) {
	_this.base.Regist(mux)
	_this.base.path += "logfile"
	_this.base.HandleRegist("getLogfiles", _this.getLogfiles)
	_this.base.HandleRegist("getLogfileByName", _this.getLogfileByName)
}

//getLogfiles 获取LOG文件
func (_this *LogfileService) getLogfiles(w http.ResponseWriter, r *http.Request) {
	files, _, err := helplib.GetFilesAndDirs(define.LogPath, "log")
	if err != nil {
		logger.Warn(err)
		fmt.Fprintln(w, "fault")
		return
	}
	bf, err := json.Marshal(files)
	if err != nil {
		logger.Warn(err)
		fmt.Fprintln(w, "fault")
		return
	}
	fmt.Fprintln(w, string(bf[:]))
}

//getLogfileByName 根据文件名获取一个LOG文件内容
func (_this *LogfileService) getLogfileByName(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		fname := GetParam(vars, "fname")
		bf, err := ioutil.ReadFile(define.LogPath + fname)
		if err != nil {
			logger.Warn(err)
			fmt.Fprintln(w, "fault")
			return
		}
		fmt.Fprintln(w, string(bf[:]))
	} else {
		fmt.Fprintln(w, "fault")
	}
}
